package com.qhgrain.api.menurolepermission.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.paas.base.modules.utils.lang.StringUtil;
import com.pubframework.common.util.datetime.DateUtil;
import com.qhgrain.api.menurolepermission.dao.RoleMapper;
import com.qhgrain.api.menurolepermission.dao.RolePermissionMapper;
import com.qhgrain.api.menurolepermission.dao.UserRoleMapper;
import com.qhgrain.api.menurolepermission.entity.Role;
import com.qhgrain.api.menurolepermission.entity.RolePermission;
import com.qhgrain.api.menurolepermission.entity.UserRole;
import com.qhgrain.api.menurolepermission.info.RoleInfo;
import com.qhgrain.api.menurolepermission.service.IRoleService;
import com.qhgrain.gway.util.UUIDUtil;

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl implements IRoleService{


	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private RolePermissionMapper rolePermissionMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	@Override
	@Transactional(readOnly = false)
	public void addRole(Role Role) {
		this.roleMapper.insert(Role);
		
	}

	@Override
	@Transactional(readOnly = false)
	public void editRole(Role role) {
		
		 this.roleMapper.updateByPrimaryKey(role);
	}


	@Override
	public void deleteByIds(String[] ids) {
		List<String> list = Arrays.asList(ids);
		
		Example example = new Example(Role.class);
		example.createCriteria().andIn("id", list);
		
		this.roleMapper.deleteByExample(example);
		
	}

	@Override
	public Role getRoleById(String roleId) {
		
		return this.roleMapper.selectByPrimaryKey(roleId);
	}

	@Override
	public void grantPermissions(String[] permissionIds, String roleId) {
		//先删掉
	//	this.rolePermissionMapper.deleteByRoleId(roleId);
				
		
		List<RolePermission> list = new ArrayList<RolePermission>();
		for(String pid: permissionIds){
			list.add(new RolePermission(UUIDUtil.getUUID(),roleId,pid));
		}
		this.rolePermissionMapper.insertBatch(list);
	}

	@Override
	public void grantUsers(String roleId, List<String> userIds) {
		List<UserRole> list = new ArrayList<UserRole>();
		for(String userId: userIds){
			list.add(new UserRole(UUIDUtil.getUUID(),roleId,userId));
		}
		this.userRoleMapper.insertBatch(list);
	}


	@Override
	public void deleteRolePermission(String roleId) {
		
		this.rolePermissionMapper.deleteByRoleId(roleId);
	}

	@Override
	public PageInfo<Role> queryPage(String roleName, String roleType,
			String status, int pageNo, int pageSize) {
		Example example = new Example(Role.class);
		Criteria c = example.createCriteria();
		if(StringUtil.isNotBlank(roleName)){
			c.andLike("name", "%"+roleName+"%");
		}
		if(StringUtil.isNotBlank(roleType)){
			c.andEqualTo("type",roleType);
		}
		if(StringUtil.isNotBlank(status)){
			c.andEqualTo("status",status);
		}
		
		example.orderBy("createDate").desc();
		Page<Role> page = PageHelper.startPage(pageNo, pageSize);
		this.roleMapper.selectByExample(example);
		return page.toPageInfo();
	}

	@Override
	public List<Role> queryList(String roleName, String roleType,
			String status, String createDate) {
		Example example = new Example(Role.class);
		Criteria c = example.createCriteria();
		if(StringUtil.isNotBlank(roleName)){
			c.andLike("roleName", "%"+roleName+"%");
		}
		if(StringUtil.isNotBlank(roleType)){
			c.andEqualTo("roleType",roleType);
		}
		if(StringUtil.isNotBlank(status)){
			c.andEqualTo("status",status);
		}
		example.orderBy("createDate").desc();
		return this.roleMapper.selectByExample(example);
	}

	@Override
	public List<Role> getAll(String userId) {
		if(StringUtil.isBlank(userId) || "null".equalsIgnoreCase(userId)){
			Example e = new Example(Role.class);
			e.createCriteria().andEqualTo("status","0");
			e.orderBy("createDate").desc();
			return this.roleMapper.selectByExample(e);
		}else{
			return this.roleMapper.queryByUser(userId);
		}
		
	}
	/**
	 * 
	 * 2016年4月6日 下午1:50:23
	 * @tags 为用户分配角色
	 * 
	 * @author zhaoyq
	 */
	@Override
	public void grantRolesForUser(List<String> roleIds, String userId) {
		List<UserRole> list = new ArrayList<UserRole>();
		for(String roleId: roleIds){
			list.add(new UserRole(UUIDUtil.getUUID(),roleId,userId));
		}
		this.userRoleMapper.insertBatch(list);
	}

	/**
	 * 根据角色ID和用户ID删除用户角色中间信息
	 */
	@Override
	public void deleteUserRole(String roleId,String userId) {
		
		Example example = new Example(UserRole.class);
		//删除所有roleId的用户角色信息
		if(StringUtils.isNotBlank(roleId)){
			example.createCriteria().andEqualTo("roleId", roleId);
		}
		//删除所有userId的用户角色信息
		if(!StringUtils.isBlank(userId)){
			example.createCriteria().andEqualTo("userId", userId);
		}
		
		this.userRoleMapper.deleteByExample(example);
		
	}

	@Override
	public Role findByRoleCode(String roleCode) {
		Example e = new Example(Role.class);
		e.createCriteria().andEqualTo("roleCode",roleCode);
		List<Role> list = this.roleMapper.selectByExample(e);
		if(list != null && list.size() > 0){
			return list.get(0);
		}
		return null;
	}

	@Transactional(readOnly = false)
	@Override
	public void insertBatch(List<RoleInfo> list) {
		if(list != null && list.size() > 0){
			List<RoleInfo> adds = new ArrayList<RoleInfo>();
			String createTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
			for(RoleInfo r : list){
				if(this.roleMapper.selectByPrimaryKey(r.getId()) == null){
					r.setCreateDate(createTime);
					adds.add(r);
				}
			}
			if(adds.size() > 0){
				this.roleMapper.insertBatch(list);
			}
		}
		
	}

	@Transactional(readOnly = false)
	@Override
	public void update(List<RoleInfo> list) {
		if(list != null && list.size() > 0){
			for(RoleInfo r : list){
				this.roleMapper.updateByInfo(r);
			}
		}
		
	}

	@Override
	public List<RoleInfo> getRolesByAppId(String appId) {
		
		return this.roleMapper.getRolesByAppId(appId);
	}
	
}
